<?php
include "otamu_config.php";

$OBJECT = 'item';
$OBJECT_TABLE = $OBJECT.'s';

$layout = "layout";
define("_VIEWPATH_","views/$OBJECT/");

if (!isset($_GET['act'])) $_GET['act'] = ''; 

class Item extends ADOdb_Active_Record
{
	var $_table = "items";
}
//ADOdb_Active_Record::ClassBelongsTo('Item','item_group','item_group_id','id'); 
//ADOdb_Active_Record::ClassBelongsTo('Item','graph_type','graph_type_id','id');



switch ($_GET['act']) {
	case "new" :
		break;

	case "create" :
		if ($_REQUEST['item']['name']=='') exitError("Sila Masukkan Nama Jabatan");
		//check if already exist group
		$sql = "SELECT name FROM items WHERE name ilike '$_REQUEST[item][name]'";
		$n = pg_num_rows(pg_query($sql));
		
		if ($n>0) exitError("Item already exists.");

		$obj = new Item();
		
		foreach ($_REQUEST['item'] as $k=>$v) {
			$obj->$k = $v;
		
		}
		//$obj->name            = $_REQUEST['name'];
		
		//print_r($obj);exit;

		if (!$obj->save()) { 
			echo $obj->ErrorMsg();exit;
			$_SESSION['flash'] = $obj->ErrorMsg();
		}else {
			$_SESSION['flash'] = ucwords($OBJECT).' has been added';
		}
		header("Location: " .$OBJECT. ".php?act=list");
		break;
		
	case "edit" :
		if (!isset($id) || $id=='') {
			exitError(ucwords($OBJECT) . " not found.");
		}
		$item = new Item();
		$item->Load('id='.$id);
		break;

	case "update" :
		if (!isset($id) || $id=='') {
			exitError(ucwords($OBJECT) . " not found.");
		}
		$new_object = ucwords($OBJECT);
		$obj = new $new_object();

		$obj->Load("id='$_REQUEST[id]'");
		print_r($obj);

		foreach ($_REQUEST[$OBJECT] as $k=>$v) {
			$obj->$k = $v;
		}
		//print_r($obj);exit;

		if (!$obj->save()) { 
			$_SESSION['flash'] = $obj->ErrorMsg();
		}else {
			$_SESSION['flash'] = ucwords($OBJECT) . ' has been updated';
		}
		header("Location: $OBJECT.php?act=list");
		
		break;

	case "destroy" :
		if (isset($id)) {
			/*$check = "SELECT DISTINCT(item_group_id) FROM items WHERE item_group_id='$id'";
			$n = pg_num_rows(pg_query($check));
			if ($n>0) {
				exitError("This group is still in use and cannot be deleted.");
			}*/
			$sql = "DELETE FROM $OBJECT_TABLE WHERE id='$id'";
			$res = pg_query($sql);
			$_SESSION['flash'] = ucwords($OBJECT) . ' has been deleted';
			header("Location: $OBJECT.php?act=list");
		}
		else {
			echo "group not found $btn";exit;
		}
		break;
	
	default :
		$act = "list";
		$res = pg_query("SELECT i.*,g.name as item_group_name,gt.name as graph_type_name FROM items i
		                 LEFT JOIN item_groups g ON g.id=i.item_group_id
						 LEFT JOIN graph_types gt ON gt.id=i.graph_type_id
						 ORDER BY name");
		
}

include _VIEWPATH_."$layout.php";

?>
